package com.tuling.code;

public class BSExists {
    /**
     * 二分查找判断一个是不是存在
     * @param arry
     * @param num
     * @return
     */
    public boolean exsits(int[] arry,int num){
        int right = arry.length - 1;
        int left = 0;
        int mid = 0;

        if(left <= right){
            mid = left +(right -left)/2;
            if(arry[mid] == num){
                return true;
            } else if (arry[mid] > num) {
                right = mid -1;
            }else{
                left = mid +1;
            }
        }
        return false;
    }

    /**
     * 二分找出小于等于num 最左位置
     * @param arry
     * @param num
     * @return
     */
    public int exsitsLeftIndex(int[] arry,int num){
        int right = arry.length - 1;
        int left = 0;
        int mid = 0;
        int index = -1;
        while (left <= right){
            mid = left + (right - left) /2;
            //符合条件还得向左边找 right 最右侧right = mid -1
            if(arry[mid]<= num){
                index = mid;
                right = mid -1;
            }else{
                left = mid +1;
            }
        }
        return index;
    }
}
